#############################################################
# File: output.py
# Function: Print graphics on screen and write files with the results
# Author: Bruno Luna
# Date: 03/02/11
# Modifications Date:
# 
#
#
#
#
#############################################################
from dolfin import *

def delfine_plot(x,  residuals,  V,  u0):
    """Plots the results as contour plots and the residuals history as x-y plot"""
    
    # Function to convert NumPy array to Dolfin vector
    def as_vector(x):
        v = Vector(len(x))
        v.set_local(x)
        return v
    
    vx = as_vector(x)
    fx = Function(V, vx)
    
    # Save solution in VTK format
    fileVtk = File("poisson.pvd")
    fileVtk << fx
    
    # Save solution in raw text format
    resList = list(residuals)
    fileTxt = open("residuals.txt","w")
    
    for res in resList:
        fileTxt.write(str(res) + "\n")
    
    fileTxt.close()
    
    # Calculate max error norm
    u_numerical = fx.vector().array()
    u0_interp = interpolate(u0, V)
    u_exact = u0_interp.vector().array()
    
    diff = abs(u_numerical - u_exact)
    print 'Max Error: %1.2E' % diff.max()
    
    # Plot solution
    plot(fx, interactive=True)
    
    import pylab
    pylab.figure(2)
    pylab.semilogy(residuals)
    pylab.show()
#############################################################
